﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;

namespace HelpDesk
{
    public partial class CrearUsuario : System.Web.UI.Page
    {
        string operacion;
        bool encontrado = true;

        protected void Page_Load(object sender, EventArgs e)
        {
            operacion = Request.QueryString["op"]; //se captura el parametro, si es Crear, Modificar, Eliminar usuario

            switch (operacion.ToLower())
            {
                case "crear":
                    btnGuardar.Text = "Guardar";
                    btnBorrar.Enabled = false;
                    lblTitulo.Text = "Crear Usuario";
                    break;
                case "modificar":
                    btnGuardar.Enabled = false;
                    btnBorrar.Text = "Buscar";
                    ddlArea.Enabled = false;
                    ddlRol.Enabled = false;
                    txtApellido.Enabled = false;
                    txtApellido2.Enabled = false;
                    txtEmail.Enabled = false;
                    txtNombre.Enabled = false;
                    txtNombre2.Enabled = false;
                    txtPassword.Visible = false;
                    txtPassword2.Visible = false;
                    txtPassword.Enabled = false;
                    txtPassword2.Enabled = false;
                    txtTelefono.Enabled = false;

                    btnGuardar.Visible = false;
                    ddlArea.Visible = false;
                    ddlRol.Visible = false;
                    txtApellido.Visible = false;
                    txtApellido2.Visible = false;
                    txtEmail.Visible = false;
                    txtNombre.Visible = false;
                    txtNombre2.Visible = false;
                    txtTelefono.Visible = false;

                    Label1.Visible = false;
                    Label2.Visible = false;
                    Label3.Visible = false;
                    Label4.Visible = false;
                    Label6.Visible = false;
                    Label7.Visible = false;
                    Label10.Visible = false;
                    Label11.Visible = false;

                    lblTitulo.Text = "Modificar Usuario";
                    break;
                case "eliminar":
                    btnGuardar.Enabled = false;
                    btnBorrar.Text = "Buscar Usuario";
                    ddlArea.Enabled = false;
                    ddlRol.Enabled = false;
                    txtApellido.Enabled = false;
                    txtApellido2.Enabled = false;
                    txtEmail.Enabled = false;
                    txtNombre.Enabled = false;
                    txtNombre2.Enabled = false;
                    txtPassword.Visible = false;
                    txtPassword2.Visible = false;
                    txtPassword.Enabled = false;
                    txtPassword2.Enabled = false;
                    txtTelefono.Enabled = false;

                    btnGuardar.Visible = false;
                    ddlArea.Visible = false;
                    ddlRol.Visible = false;
                    txtApellido.Visible = false;
                    txtApellido2.Visible = false;
                    txtEmail.Visible = false;
                    txtNombre.Visible = false;
                    txtNombre2.Visible = false;
                    txtTelefono.Visible = false;

                    Label1.Visible = false;
                    Label2.Visible = false;
                    Label3.Visible = false;
                    Label4.Visible = false;
                    Label6.Visible = false;
                    Label7.Visible = false;
                    Label10.Visible = false;
                    Label11.Visible = false;
                    btnBorrar.Text = "Buscar";
                    lblTitulo.Text = "Eliminar Usuario";
                    break;
            }

            QueryBuilder Consulta = new QueryBuilder();
            string sql = "Select DESCRIPCION from AREA_TRABAJO";
            string sql2 = "Select TIPO from PERMISO";
            DataTable datos1 = Consulta.EjecutarQuery(sql);
            DataTable datos2 = Consulta.EjecutarQuery(sql2);
            for (int i = 0; i < datos1.Rows.Count; i++)
            {
                ddlArea.Items.Add(datos1.Rows[i].ItemArray[0].ToString());

            }
            for (int i = 0; i < datos2.Rows.Count; i++)
            {
                ddlRol.Items.Add(datos2.Rows[i].ItemArray[0].ToString());
            }
        }

        protected void btnGuardar_Click(object sender, EventArgs e)
        {
            QueryBuilder Consulta = new QueryBuilder();
            DataTable GetID = new DataTable();
            Utilitario Utilidades = new Utilitario();
            string sql;

            GetID = Consulta.EjecutarQuery("select ID_Permiso from permiso where tipo='" + ddlRol.SelectedItem.Text + "'");
            int id_rol = Convert.ToInt32(GetID.Rows[0].ItemArray[0]);
            GetID = Consulta.EjecutarQuery("select ID_AREA from AREA_TRABAJO where DESCRIPCION ='" + ddlArea.SelectedItem.Text + "'");
            int id_area = Convert.ToInt32(GetID.Rows[0].ItemArray[0]);

            if (string.Compare(operacion, "crear") == 0)
            {              
                sql = "INSERT INTO USUARIO(ID_USUARIO, NOMBRES, APELLIDOS, EMAIL, TELEFONO, STATUS, " +
                    "PASSWORD, FECHA_CREADO, USUARIO_CREADO, PERMISOS, AREA) VALUES('" +
                    txtUsuario.Text + "', '" + txtNombre.Text + " " + txtNombre2.Text + "', '" + txtApellido.Text + " " + txtApellido2.Text +
                    "', '" + txtEmail.Text + "', " + txtTelefono.Text + ", 'A', '" + Utilidades.Encriptar_Password(txtPassword.Text) + "', sysdate, '" +
                    Session["Usuario"].ToString() + "', " + id_rol +", " + id_area + ")";

                try
                {
                    Consulta.EjecutarNoQuery(sql);
                    Response.Write("<script language=javascript>alert('Se ha creado el usuario con exito!');</script>");
                }
                catch
                {
                    Response.Write("<script language=javascript>alert('Error al crear usuario!');</script>");
                }
                btnBorrar.Text = "Borrar";
                btnGuardar.Text = "Guardar";
                btnGuardar.Enabled = false;
            }
            else if(string.Compare(operacion, "eliminar") == 0)
            {
                if (string.Compare(HiddenField1.Value, "A") == 0)
                {
                    try
                    {
                        Consulta.EjecutarNoQuery("Update Usuario set STATUS='I' where ID_Usuario='" + txtUsuario.Text + "'");
                    }
                    catch {
                        Response.Write("<script language=javascript>alert('Ha ocurrido un problema al eliminar!');</script>");
                    }
                    Response.Write("<script language=javascript>alert('Se ha eliminado el usuario con exito!');</script>");
                }
                else if (string.Compare(HiddenField1.Value, "I") == 0)
                {
                    Response.Write("<script language=javascript>alert('El usuario no existe!');</script>");
                }
                btnBorrar.Text = "Buscar";
                btnGuardar.Text = "Eliminar";
                btnGuardar.Enabled = false;
            }
            else if (string.Compare(operacion, "modificar") == 0)
            {
                sql = "UPDATE USUARIO SET NOMBRES='" + txtNombre.Text + " " + txtNombre2.Text + "', APELLIDOS='" + txtApellido.Text + " " + txtApellido2.Text +
                    "', EMAIL='" + txtEmail.Text + "', TELEFONO=" + txtTelefono.Text + ", PERMISOS=" + id_rol + ", AREA=" + id_area + " WHERE ID_USUARIO='" + txtUsuario.Text + "'";

                try
                {
                    Consulta.EjecutarNoQuery(sql);
                    Response.Write("<script language=javascript>alert('Se ha modificado el usuario con exito!');</script>");
                }
                catch
                {
                    Response.Write("<script language=javascript>alert('Error al modificar usuario!');</script>");
                }
                btnBorrar.Text = "Buscar";
                btnGuardar.Text = "Guardar";
                btnGuardar.Enabled = false;
            }
            txtApellido.Text = "";
            txtApellido2.Text = "";
            txtEmail.Text = "";
            txtNombre.Text = "";
            txtNombre2.Text = "";
            txtPassword.Text = "";
            txtPassword2.Text = "";
            txtTelefono.Text = "";
        }

        public void Select()
        {
            QueryBuilder Consulta = new QueryBuilder();
            DataTable GetData = new DataTable();
            Utilitario Utilidades = new Utilitario();
            string sql;
            string dato_buscar;
            dato_buscar = txtUsuario.Text;

            if (dato_buscar != "")
            {
                sql = "Select * from USUARIO WHERE ID_USUARIO='" + dato_buscar + "'";
                GetData = Consulta.EjecutarQuery(sql);

                if (GetData.Rows.Count != 0)
                {
                    string[] Nombres = GetData.Rows[0].ItemArray[1].ToString().Split(' ');
                    string[] Apellidos = GetData.Rows[0].ItemArray[2].ToString().Split(' ');
                    txtNombre.Text = Nombres[0];
                    txtNombre2.Text = Nombres[1];
                    txtApellido.Text = Apellidos[0];
                    txtApellido2.Text = Apellidos[1];
                    txtEmail.Text = GetData.Rows[0].ItemArray[3].ToString();
                    txtTelefono.Text = GetData.Rows[0].ItemArray[4].ToString();
                    HiddenField1.Value = GetData.Rows[0].ItemArray[5].ToString();

                    sql = "Select DESCRIPCION from AREA_TRABAJO where ID_Area =" + GetData.Rows[0].ItemArray[10].ToString();
                    string sql2 = "Select TIPO from PERMISO where ID_Permiso =" + GetData.Rows[0].ItemArray[9].ToString();
                    DataTable datos1 = Consulta.EjecutarQuery(sql);
                    DataTable datos2 = Consulta.EjecutarQuery(sql2);
                    ddlArea.SelectedItem.Text = datos1.Rows[0].ItemArray[0].ToString();
                    ddlRol.SelectedItem.Text = datos2.Rows[0].ItemArray[0].ToString();
                }

                else
                {
                    Response.Write("<script language=javascript>alert('Usuario no encontrado por favor ingrese uno valido');</script>");
                    btnGuardar.Enabled = false;
                    encontrado = false;
                    Page_Load(null, null);
                }
            }

            else
            {
                Response.Write("<script language=javascript>alert('Por favor ingrese un usuario a buscar!');</script>");
            }
            Page_Load(null, null);
        }

        protected void btnBorrar_Click1(object sender, EventArgs e)
        {
            //Buscar
            Select();
            if (string.Compare(operacion, "Eliminar") == 0)
            {
                if (encontrado == true)
                {
                    btnGuardar.Text = "Eliminar";
                    btnGuardar.Enabled = true;
                    ddlArea.Enabled = false;
                    ddlRol.Enabled = false;
                    txtApellido.Enabled = false;
                    txtApellido2.Enabled = false;
                    txtEmail.Enabled = false;
                    txtNombre.Enabled = false;
                    txtNombre2.Enabled = false;
                    txtTelefono.Enabled = false;

                    btnGuardar.Visible = true;
                    ddlArea.Visible = true;
                    ddlRol.Visible = true;
                    txtApellido.Visible = true;
                    txtApellido2.Visible = true;
                    txtEmail.Visible = true;
                    txtNombre.Visible = true;
                    txtNombre2.Visible = true;
                    txtTelefono.Visible = true;

                    Label1.Visible = true;
                    Label2.Visible = true;
                    Label3.Visible = true;
                    Label4.Visible = true;
                    Label6.Visible = true;
                    Label7.Visible = true;
                    Label10.Visible = true;
                    Label11.Visible = true;
                }
            }
            else if (string.Compare(operacion, "modificar") == 0)
            {
                if (encontrado == true)
                {
                    btnGuardar.Text = "Guardar";
                    btnGuardar.Enabled = true;
                    ddlArea.Enabled = true;
                    ddlRol.Enabled = true;
                    txtApellido.Enabled = true;
                    txtApellido2.Enabled = true;
                    txtEmail.Enabled = true;
                    txtNombre.Enabled = true;
                    txtNombre2.Enabled = true;
                    txtTelefono.Enabled = true;

                    btnGuardar.Visible = true;
                    ddlArea.Visible = true;
                    ddlRol.Visible = true;
                    txtApellido.Visible = true;
                    txtApellido2.Visible = true;
                    txtEmail.Visible = true;
                    txtNombre.Visible = true;
                    txtNombre2.Visible = true;
                    txtTelefono.Visible = true;

                    Label1.Visible = true;
                    Label2.Visible = true;
                    Label3.Visible = true;
                    Label4.Visible = true;
                    Label6.Visible = true;
                    Label7.Visible = true;
                    Label10.Visible = true;
                    Label11.Visible = true;
                }
            }
        }

        protected void HiddenField1_ValueChanged(object sender, EventArgs e)
        {

        }

    }
}
